/**
 * Created by Adi(adi@imeth.cn) on 2018/9/8.
 */
import React from 'react';
import { autobind } from 'core-decorators';
import PropTypes from 'prop-types';
import { Tabs, Row, Col, Form, Input } from 'antd/lib/index';

const FormItem = Form.Item;

const TabPane = Tabs.TabPane;

@Form.create()
@autobind
class TabsView extends React.Component {

  static propTypes = {
    tabList: PropTypes.array.isRequired,
    defaultActiveKey: PropTypes.number, // 初始化选中面板的 key，如果没有设置 activeKey
    size: PropTypes.string,  // 大小，提供 large default 和 small 三种大小
    tabBarGutter: PropTypes.number, // tabs 之间的间隙
    tabPosition: PropTypes.string,  // 页签位置，可选值有 top right bottom left
    onChange: PropTypes.func,  // 切换面板的回调
    onTabClick: PropTypes.func,  // tab 被点击的回调
    tabTitle: PropTypes.oneOf([PropTypes.string, PropTypes.element]), // 选项卡头显示文字
  };

  static defaultProps = {
    size: 'default',
    tabPosition: 'top',
    tabBarGutter: 0,
    defaultActiveKey: 1,
  };

  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    let { size, tabBarGutter, defaultActiveKey, tabPosition } = this.props;
    return (
      <Tabs tabPosition={tabPosition} tabBarGutter={tabBarGutter} size={size} onChange={this._onChange}>
        {this.renderTabList()}
      </Tabs>
    );
  }

  renderTabList() {
    let { tabList } = this.props;
    let list = [];
    for (let i = 0; i < tabList.length; i++) {
      list.push(
        <TabPane tab={tabList[i].tabTitle} key={tabList[i].key}>
          <Row type="flex" justify="start" align="middle">
            {this.renderFormItem(tabList[i].content)}
          </Row>

        </TabPane>,
      );
    }
    return list;
  }

  // 遍历渲染表单子项
  renderFormItem(formItemList) {
    let { form } = this.props;
    let { getFieldDecorator } = form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    let list = [];
    let col = null;
    let pull = 0;
    let push = 0;
    for (let i = 0; i < formItemList.length; i++) {
      col = formItemList[i].col ? formItemList[i].col : 12;
      pull = formItemList[i].pull ? formItemList[i].pull : pull;
      push = formItemList[i].push ? formItemList[i].push : push;
      list.push(
        <Col span={col} key={i} pull={pull} push={push}>
          <FormItem style={{ display: 'flex' }} label={formItemList[i].label} {...formItemLayout}>
            {getFieldDecorator(formItemList[i].value, {
              rules: formItemList[i].rules,
              initialValue: formItemList[i].initialValue,
            })(formItemList[i].renderItem)}
          </FormItem>
        </Col>,
      );
    }
    return list;
  }

  _onChange(activeKey) {
    let { onChange } = this.props;
    onChange && onChange(activeKey);
  }
}

export default TabsView;
